﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using FluentNHibernate.Mapping;

namespace LibYanu.DAO
{
    public class PersistentModelGeneratorBase : IPersistenceModelGenerator
    {

        public virtual global::FluentNHibernate.Automapping.AutoPersistenceModel Generate()
        {
            return new global::FluentNHibernate.Automapping.AutoPersistenceModel();
        }

        public bool HasAuto
        {
            get;
            protected set;
        }

        protected List<Type> classMaps = new List<Type>();
        public IEnumerable<Type> ClassMaps
        {
            get { return classMaps; }
        }

        private IEnumerable<Assembly> hbmMaps = new List<Assembly>();
        public IEnumerable<Assembly> HbmMaps
        {
            get { return hbmMaps; }
        }

        private static Func<Type, bool> classMapFilter = t => t.BaseType != null && t.BaseType.IsGenericType && t.BaseType.GetGenericTypeDefinition() == typeof(ClassMap<>);

        private List<Type> ignoreType = new List<Type>();

        protected void AddClassMapFromAssemblyOf<T>()
        {
            var clsMaps = typeof(T).Assembly
                .GetTypes()
                    .Where(classMapFilter);
            if (clsMaps.Any())
            {
                ignoreType.AddRange(clsMaps.Select(t => t.BaseType.GetGenericArguments()[0]).ToList());
                classMaps.AddRange(clsMaps);
            }
        }

        protected bool GetAutoMappingFilter(Type t)
        {
            return !ignoreType.Contains(t) && t.GetInterfaces().Any(x =>
                 x.IsGenericType && x.GetGenericTypeDefinition() == typeof(IEntityWithTypedId<>));
        }

    }
}
